<template>
  <div class="register-view">

    <div class="header">
      <div class="nav-bar-left-logo">
        <img src="../../assets/img/login/img_logo.png">
      </div>
    </div>

    <div class="center">
      <!--      <div class="shadow"></div>-->
      <div class="center-content">
        <div class="left">
          <div class="title">
            手机号注册
            <a
              class="backTxt"
              @click="backClick"
            >返回前页</a>
          </div>

          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-position="left"
            label-width="80px"
          >
            <el-form-item
              label="手机号"
              prop="mobile"
            >
              <el-input
                v-model="ruleForm.mobile"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="验证码"
              prop="code"
            >
              <div class="codeView">
                <el-input
                  v-model="ruleForm.code"
                  placeholder="请输入验证码"
                ></el-input>

                <el-button
                  round
                  @click="smsClick"
                  :disabled="disable"
                >{{codeStr}}</el-button>
              </div>
            </el-form-item>
            <el-form-item
              label="密码"
              prop="psw"
            >
              <el-input
                v-model="ruleForm.psw"
                show-password
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="确认密码"
              prop="pswTwo"
            >
              <el-input
                v-model="ruleForm.pswTwo"
                show-password
                placeholder="请再次输入密码"
              ></el-input>
            </el-form-item>
          </el-form>

          <div class="left-item">
            <el-button
              type="primary"
              @click="registerClick"
            >注册</el-button>
          </div>

        </div>
      </div>

      <footerCom />

    </div>

  </div>
</template>

<script>
import { getQiniu, existMobile } from "../../api/common";
import area from "../../utils/area";
import { registry } from "../../api/user";
import { sendSms } from "../../api/common";
import footerCom from "../../components/footerCom.vue";

export default {
  name: "register",
  components: {
    footerCom
  },
  data: function() {
    var pswValidator = (rule, value, callback) => {
      if (value != this.ruleForm.psw) {
        callback("两次密码不一致");
      } else {
        callback();
      }
    };
    return {
      timer: null,
      disable: false,
      count: "",
      phone: "",
      code: "",
      psw: "",
      pswTwo: "",
      codeStr: "发送验证码",
      isInformation: false,

      options: [],
      data: {
        name: "",
        phone: "",
        value: ""
      },

      domain: "http://upload.qiniu.com", // 七牛云的上传地址
      qiniuToken: {}, //上传到七牛的token
      imageUrl: "",

      ruleForm: {
        mobile: "",
        code: "",
        psw: "",
        pswTwo: ""
      },
      rules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "请输入正确手机号" }
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        psw: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/,
            message: "请输入6至12位字母和数字组合密码"
          }
        ],
        pswTwo: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: pswValidator, trigger: "blur" }
        ]
      }
    };
  },
  mounted: function() {
    this.options = area.citys;
  },
  methods: {
    backClick: function() {
      this.$router.back();
    },
    handleChange: function(value) {},
    smsClick: function() {
      if (this.ruleForm.mobile == "") {
        this.$message.error("请输入手机号");
        return;
      } else if (!this.RX.PHONE_RX.test(this.ruleForm.mobile)) {
        this.$message.error("请输入正确手机号");
        return;
      }

      existMobile({ mobile: this.ruleForm.mobile })
        .then(res => {
          if (res.code == 200) {
            if (res.data.is_exits) {
              this.$message.error("手机号已注册");
            } else {
              this.sendSms();
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {});
    },
    sendSms: function() {
      let data = {
        mobile: this.ruleForm.mobile,
        sms_key: "sms_auth"
      };
      sendSms(data).then(res => {
        if (res.code == 200) {
          this.startTimer();
          this.$message({
            message: "验证码已发送",
            type: "success"
          });
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    pswBlur: function() {
      if (!this.RX.PASSWORD_RX.test(this.psw)) {
        this.$message.error("请输入6至12位字母和数字组合密码");
      }
    },
    registerClick: function() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let data = {
            mobile: this.ruleForm.mobile,
            valid_code: this.ruleForm.code,
            pwd: this.ruleForm.psw
          };
          registry(data).then(res => {
            if (res.code == 200) {
              this.$message({
                message: "注册成功",
                type: "success"
              });

              this.loginUser();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    loginUser: function() {
      let data = {
        account: this.ruleForm.mobile,
        pwd: this.ruleForm.psw
      };
      this.$store
        .dispatch("user/login", data)
        .then(code => {
          if (code != 200) {
            this.$router.push({ name: "enter" });
          } else {
            // setAutomatic(this.automatic);
            // this.$store.dispatch("setting/setSystemSetting").then(()=>{
            //     this.$store.dispatch("setting/setPrintSetting").catch((e) => {});
            // }).catch((e) => {});
            // this.$store.dispatch("setting/updataCheckTreatment",1)
            // this.$store.dispatch("setting/updataCheckTreatment",2)
            //
            // this.$store.dispatch("user/getInfo").then((user)=>{
            //     if (this.$route.query.backUrl){
            //         this.$router.push({name:this.$route.query.backUrl})
            //     }else {
            //         if (user.menus.length && user.menus.length > 0){
            //             let index = 0;
            //             for (let i = 0; i < user.menus.length; i++){
            //                 if (user.menus[i].code == "health"){
            //                     index = i;
            //                     break;
            //                 }
            //             }
            //             this.$router.push(user.menus[index].path)
            //         }else {
            //             this.$router.push("clinicManagement")
            //         }
            //     }
            // })
          }
        })
        .catch(msg => {
          this.$message.error(msg);
        });
    },
    startTimer: function() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.disable = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
            this.codeStr = this.count + "(s)";
          } else {
            this.codeStr = "重新发送";
            this.disable = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    loginClick: function() {
      this.$router.push("/login");
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 15;

      if (!isJPGorPNG) {
        this.$message({
          type: "error",
          message: "上传图片只能是jpg、png、jpeg格式！",
          duration: 1500
        });
        return false;
      }
      if (!isLt2M) {
        this.$message({
          type: "error",
          message: `上传图片大小不能超过15M!`,
          duration: 1500
        });
        return false;
      }
      if (isJPGorPNG && isLt2M) {
        return getQiniu().then(res => {
          this.qiniuToken = {
            token: res.data
          };
        });
      }
    },
    handlePictureCardPreview: function() {},
    handleRemove: function() {}
  }
};
</script>

<style lang="scss">
@import "@/assets/scss/login/register.scss";
</style>
